<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="pageData.queryData" layout="inline">
          <a-form-item label="日期">
            <a-range-picker  popup-container="html" 
              :style="{ width: '300px' }"
              class="bacClass"
              v-model="pageData.queryData.createTimeArr"
            />
          </a-form-item>
          <a-form-item label="流转卡号">
            <a-input
              @press-enter="selectHandler"
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="pageData.queryData.flowCardCode"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          v-if="pageData.toolbarShow"
          :items="['查询', '新增', '删除', '提交']"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
          @tj="submittHandler"
        >
        </Toolbar>
        <Toolbar v-else :items="['查询']" @select="selectHandler"> </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" default-active-key="1" @change="tabsChange">
        <a-tab-pane title="未处理" key="1"> </a-tab-pane>
        <a-tab-pane title="已处理" key="2"> </a-tab-pane>
      </a-tabs>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 85%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="pageData.disposeState == 0 ? tc : tc1"
        :localeText="localeText1"
        :suppressRowClickSelection="true"
      ></AgGridVuesCopys>
    </template>

    <paginationCopys
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="nextDoRefreshPage"
      @page-size-change="nextDoRefreshSize"
      style="justify-content: center"
    />

    <a-drawer
      placement="bottom"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      height="70%"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm" layout="horizontal">
          <a-row class="grid-demo" :gutter="{ md: 8, lg: 24, xl: 32 }">
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="流转卡号"
                field="flowCardCode"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '流转卡号必填' }]"
              >
                <a-input class="bacClass" v-model="dataForm.flowCardCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="开单日期"
                field="billingDate"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '开单日期必填' }]"
              >
                <a-date-picker  popup-container="html" 
                  class="bacClass"
                  v-model="dataForm.billingDate"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="生产车间"
                field="workshop"
              >
                <a-input class="bacClass" v-model="dataForm.workshop" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="制单人"
                field="touchingPerson"
              >
                <a-input class="bacClass" v-model="dataForm.touchingPerson" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="客户名称"
                field="customerName"
              >
                <a-input class="bacClass" v-model="dataForm.customerName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="客户订单号"
                field="clientOrderNumber"
              >
                <a-input class="bacClass" v-model="dataForm.clientOrderNumber" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="布号" field="greyCode">
                <a-input class="bacClass" v-model="dataForm.greyCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="品名" field="gradeName">
                <a-input class="bacClass" v-model="dataForm.gradeName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="色号"
                field="colourNumber"
              >
                <a-input class="bacClass" v-model="dataForm.colourNumber" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="色称" field="colourName">
                <a-input class="bacClass" v-model="dataForm.colourName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="纱批" field="yarnBatch">
                <a-input class="bacClass" v-model="dataForm.yarnBatch" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="回修部门"
                field="returnRepairs"
              >
                <a-input class="bacClass" v-model="dataForm.returnRepairs" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="坯布名称"
                field="greigeName"
              >
                <a-input class="bacClass" v-model="dataForm.greigeName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="坯布编号"
                field="greigeCode"
              >
                <a-input class="bacClass" v-model="dataForm.greigeCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="客户要求门幅"
                field="efficacious"
              >
                <a-input class="bacClass" v-model="dataForm.efficacious" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="客户要求克重"
                field="gramWeight"
              >
                <a-input-number class="bacClass" v-model="dataForm.gramWeight" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="原匹数" field="houseNum">
                <a-input-number class="bacClass" v-model="dataForm.houseNum" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="原重量"
                field="finishedWeight"
              >
                <a-input-number class="bacClass" v-model="dataForm.finishedWeight" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="异常匹数"
                field="anomalyHouseNum"
              >
                <a-input-number class="bacClass" v-model="dataForm.anomalyHouseNum" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label-col-flex="pageData.labelColFlex"
                label="异常重量"
                field="finishedWeightAnomaly"
              >
                <a-input-number class="bacClass" v-model="dataForm.finishedWeightAnomaly" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item :label-col-flex="pageData.labelColFlex" label="备注" field="remark">
                <a-textarea class="bacClass" v-model="dataForm.remark" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import { useTable, usePagination, useTableColumn } from '@/hooks/table'

  import { ref, reactive, onMounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import 'ag-grid-community/styles/ag-grid.css'
  import 'ag-grid-community/styles/ag-theme-alpine.css'
  import { localeText } from '@/api/aggridZw'
  

  interface paramData {
    id: any
    flowCardCode: string | undefined
    billingDate: string | undefined
    workshop: string | undefined
    touchingPerson: string | undefined
    customerName: string | undefined
    clientOrderNumber: string | undefined
    greyCode: string | undefined
    gradeName: string | undefined
    colourNumber: string | undefined
    colourName: string | undefined
    yarnBatch: string | undefined
    returnRepairs: string | undefined
    greigeName: string | undefined
    greigeCode: string | undefined
    efficacious: string | undefined
    houseNum: any
    anomalyHouseNum: any
    gramWeight: any
    finishedWeight: any
    finishedWeightAnomaly: any
    disposeState: any
    remark: string | undefined
  }

  export default {
    //成检异常登记
    name: 'AbnormalProductInspection',
    setup() {
      //隐藏显示头部
      const headerShow = ref<boolean>(true)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        theight: number
        rHeight: number | undefined
        labelColFlex: string
        queryData: any
        toolbarShow: any
        disposeState: any
      }>({
        showAdd: false,
        sideTitle: '新增成检异常登记',
        dropDownData: '',
        pageLoading: false,
        theight: 0,
        rHeight: 0,
        labelColFlex: '120px',
        queryData: {
          flowCardCode: '',
          createTimeArr: [],
        },
        toolbarShow: true,
        disposeState: 0,
      })
      const dataForm = reactive<paramData>({
        id: null,
        flowCardCode: '',
        billingDate: '',
        workshop: '',
        touchingPerson: '',
        customerName: '',
        clientOrderNumber: '',
        greyCode: '',
        gradeName: '',
        colourNumber: '',
        colourName: '',
        yarnBatch: '',
        returnRepairs: '',
        greigeName: '',
        greigeCode: '',
        efficacious: '',
        houseNum: null,
        anomalyHouseNum: null,
        gramWeight: null,
        finishedWeight: null,
        finishedWeightAnomaly: null,
        disposeState: null,
        remark: '',
      })
      //查询列表
      onMounted(() => {
        selectHandler()
      })

      //切换分页
      const nextDoRefreshPage = (val: any) => {
        pagination.page = val
        doRefresh()
      }
      const nextDoRefreshSize = (val: any) => {
        pagination.pageSize = val
        doRefresh()
      }
      const pagination = usePagination(doRefresh)
      const table = useTable()
      function doRefresh() {
        pageData.pageLoading = true
        if (pageData.queryData.createTimeArr == undefined) {
          pageData.queryData.createTimeArr = []
        }
        post({
          url: 'dwQms/AbnormalRegister/getPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            flowCardCode: pageData.queryData.flowCardCode,
            startDate: pageData.queryData.createTimeArr[0],
            endDate: pageData.queryData.createTimeArr[1],
            disposeState: pageData.disposeState,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.data)
              pagination.setTotalSize(data.total)
              gridOption.value.setRowData(data.data)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      //------新增、修改页面开始------
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        dataForm.billingDate = new Date()
        dataForm.touchingPerson = JSON.parse(
          sessionStorage.getItem('userLoginData') as any
        ).username
        pageData.showAdd = true
        pageData.sideTitle = '新增成检异常登记'
        // selectDepts()
      }
      const editHandler = (record: paramData) => {
        for (var key in record) {
          dataForm[key] = record[key]
        }
        pageData.sideTitle = '修改成检异常登记'
        pageData.showAdd = true
      }

      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle === '新增成检异常登记') {
              post({
                url: 'dwQms/AbnormalRegister/insert',
                data: [dataForm],
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()

                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  selectHandler()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            } else {
              post({
                url: 'dwQms/AbnormalRegister/update',
                data: [dataForm],
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  selectHandler()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      }
      //------新增、修改页面结束------
      //------删除方法开始------
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: 'dwQms/AbnormalRegister/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            }).then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })

                pagination.page = 1
                selectHandler()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      function selectDepts() {
        post({
          url: 'org/baCompany/getTreeCompanyByUser',
          data: {},
        }).then((res: any) => {
          if (res.code === 200) {
            console.log(res)
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            })
          }
        })
      }
      //------删除方法结束------

      // 表格准备事件
      const tableColumns = useTableColumn([
        {
          title: '系统编号',
          key: 'id',
          dataIndex: 'id',
          width: 150,
        },
        {
          title: '流转卡号',
          key: 'flowCardCode',
          dataIndex: 'flowCardCode',
        },
        {
          title: '客户名称',
          key: 'customerName',
          dataIndex: 'customerName',
        },
        {
          title: '客户订单号',
          key: 'clientOrderNumber',
          dataIndex: 'clientOrderNumber',
        },
        {
          title: '布号',
          key: 'greyCode',
          dataIndex: 'greyCode',
        },
        {
          title: '色号',
          key: 'colourNumber',
          dataIndex: 'colourNumber',
        },
        {
          title: '色称',
          key: 'colourName',
          dataIndex: 'colourName',
        },
        {
          title: '坯布编号',
          key: 'greigeCode',
          dataIndex: 'greigeCode',
        },

        {
          title: '坯布名称',
          key: 'greigeName',
          dataIndex: 'greigeName',
        },
        {
          title: '客户要求',
          children: [
            {
              headerName: '门幅',
              field: 'efficacious',
              width: 100,
            },
            {
              headerName: '克重',
              field: 'gramWeight',
              width: 100,
            },
          ],
        },
        {
          title: '原',
          children: [
            {
              headerName: '匹数',
              field: 'houseNum',
              width: 100,
            },
            {
              headerName: '重量',
              field: 'finishedWeight',
              width: 100,
            },
          ],
        },
        {
          title: '异常',
          children: [
            {
              headerName: '匹数',
              field: 'anomalyHouseNum',
              width: 100,
            },
            {
              headerName: '重量',
              field: 'finishedWeightAnomaly',
              width: 100,
            },
          ],
        },
        {
          title: '回修部门',
          key: 'returnRepairs',
          dataIndex: 'returnRepairs',
        },

        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'act',
          width: 150,
          fixed: 'right',
        },
      ])
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: o.width,
          children: o.children,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = o.fixed
          obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
              }
            },
          }
        }
        return obj
      })
      let tc1: any[] = tableColumns.map((o) => {
        let obj: any = {}
        if (o.slotName !== 'act') {
          obj = {
            headerName: o.title,
            field: o.key,
            pinned: o['fixed'],
            width: o.width,
            children: o.children,
          }
        }
        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      tc1 = a.concat(tc1)
      const localeText1: any = ref(localeText)
      //切换tab
      const tabsChange = (e: string | number) => {
        if (e === '1') {
          pageData.toolbarShow = true
          pageData.disposeState = 0
        } else {
          pageData.toolbarShow = false
          pageData.disposeState = 1
        }
        selectHandler()
      }
      const submittHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error({
            content: '请至少选择一条！',
            duration: 5000,
          })
          return
        }
        var ids = gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        })
        const data: { id: any; disposeState: string }[] = []
        for (var i = 0; i < ids.length; i++) {
          data.push({
            id: ids[i],
            disposeState: '1',
          })
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认提交选中的数据?',
          onOk() {
            post({
              url: 'dwQms/AbnormalRegister/update',
              data: data,
            }).then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '提交成功',
                  duration: 5000,
                })

                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '提交失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      return {
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        pagination,
        table,
        pageData,
        editHandler,
        selectHandler,
        headerShow,
        nextDoRefreshPage,
        nextDoRefreshSize,
        defaultColDef,
        localeText1,
        tc,
        gridReady,
        tc1,
        gridOption,
        tabsChange,
        submittHandler,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
